package com.WaVel.service.impl;

import com.Emplyment.dto.StudyMaterialDto;
import com.Emplyment.vo.StudyMaterialsVo;
import com.WaVel.mapper.StudyMaterialMapper;
import com.WaVel.service.StudyMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
@Slf4j
public class StudyMaterialServiceImpl implements StudyMaterialService {

    @Autowired
    private StudyMaterialMapper studyMaterialMapper;

    @Override
    public List<StudyMaterialDto> getStudyMaterial() {
        List<StudyMaterialDto> studyMaterial = studyMaterialMapper.getStudyMaterial();
        return studyMaterial;
    }

    @Override
    public void addStudyMaterial(MultipartFile file, String fileName) {

        try {
            byte[] downloadFileContent = StreamUtils.copyToByteArray(file.getInputStream());
            Double size = Double.valueOf(file.getSize());
            BigDecimal fileSize = new BigDecimal(size/1024/1024);
            // 2. 设置保留两位小数，四舍五入模式
            fileSize = fileSize.setScale(2, RoundingMode.HALF_UP);

            StudyMaterialsVo studyMaterialsVo = StudyMaterialsVo.builder()
                            .fileName(fileName)
                            .fileSize(fileSize+"MB")
                            .fileType(file.getContentType())
                            .file(downloadFileContent)
                            .build();

            studyMaterialMapper.addStudyMaterial(studyMaterialsVo);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteStudyMaterial(Integer id) {
        studyMaterialMapper.deleteStudyMaterial(id);
    }

    @Override
    public StudyMaterialsVo getStudyMaterialById(Integer id) {
        StudyMaterialsVo studyMaterialsVo = studyMaterialMapper.getStudyMaterialById(id);
        return studyMaterialsVo;
    }
}
